from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
from .forms import UserRegisterForm, UserLoginForm
from .models import LoginUser


def user_register(request):
    """
    用户注册入口
    :param request:
    :return:
    """
    context = dict()
    form = UserRegisterForm()
    if request.method == "POST":
        url_name = 'register_fail'
        form = UserRegisterForm(request.POST, request.FILES)
        if form.is_valid():
            result = form.save()
            if result:
                url_name = 'register_success'
        else:
            context['form'] = form
            return render(request, "users/register_fail.html", context)
        return HttpResponseRedirect(reverse("users:" + url_name))
    context['form'] = form
    return render(request, "users/register.html", context)


def user_register_success(request):
    context = dict()
    return render(request, "users/register_success.html", context)


def user_register_fail(request):
    context = dict()
    return render(request, "users/register_fail.html", context)


def user_login(request):
    context = dict()
    form = UserLoginForm()
    if request.method == "POST":
        form = UserLoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = LoginUser.objects.filter(username=username, password=password)
            if user:
                user = user[0]
                login_user = dict(username=user.username,
                                  portrait=str(user.portrait),
                                  nickname=user.nickname)
                request.session['login_user'] = login_user
                return HttpResponseRedirect(reverse("users:user_index"))
            else:
                context['error_message'] = "账号或密码错误！"

    context['form'] = form
    return render(request, "users/user_login.html", context)


def user_index(request):
    context = dict()
    login_user = request.session.get("login_user", None)
    if not login_user:
        return HttpResponseRedirect(reverse("users:user_login"))
    context['user'] = login_user
    context['login_user'] = LoginUser.objects.get(username=login_user['username'])

    return render(request, "users/index.html", context)


def user_logout(request):
    login_user = request.session.get('login_user', None)
    if login_user:
        request.session.pop("login_user")
        # request.session['login_user'] = None
        print(dir(request.session))
    return HttpResponseRedirect(reverse("users:user_login"))
